<?php
/**
 * Created by PhpStorm
 * User: 龍zero
 * Date: 2022-04-14
 * Time: 11:05
 */

namespace App\Service;


use App\Lib\Tools\Paginator;
use App\Model\LinLog;
use Hyperf\Di\Annotation\Inject;

class LogService
{
//    /**
//     * 自定义分页返回对象
//     * @Inject()
//     * @var Paginator
//     */
//    private $paginator;

    public function createLog($template,$permission,$userId,$username,$method,$path,$status){
        $log = new LinLog();
        $log->message = $template;
        $log->user_id = $userId;
        $log->username = $username;
        $log->status_code = $status;
        $log->method = $method;
        $log->path = $path;
        $log->permission = $permission;
        $log->save();
    }

    public function getLogPage($page,$count,$name,$start,$end){
        $where = function($q)use($name,$start,$end){
            if($name){
                $q->where('username',$name);
	        }
            if($start && $end){
                $q->whereBetween('create_time',[$start,$end]);
            }
		};

//        $query =  LinLog::where($where)->orderBy('create_time','desc');
//        return  $this->paginator->page($query,$count,$page);
        return  LinLog::where($where)->orderBy('create_time','desc')->paginate((int)$count,['*'],'page',(int)$page);

    }

    public function searchLogPage($page,$count,$name,$keyword,$start,$end){
        $where = function($q)use($name,$keyword,$start,$end){
            if($name){
                $q->where('username',$name);
            }
            if($keyword){
                $q->where('message','like',"%{$keyword}%");
            }
            if($start && $end){
                $q->whereBetween('create_time',[$start,$end]);
            }
        };
//        $query =  LinLog::where($where)->orderBy('create_time','desc');
//        return  $this->paginator->page($query,$count,$page);
        return   LinLog::where($where)->orderBy('create_time','desc')->paginate((int)$count,['*'],'page',(int)$page);
    }

    public function getUserNamePage($page,$count){
//        $query =  LinLog::groupBy('username')->havingRaw('count(username) > ?',[0]);
//        return  $this->paginator->page($query,$count,$page,'username');
          return LinLog::groupBy('username')->havingRaw('count(username) > ?',[0])->paginate((int)$count,['*'],'page',(int)$page);
    }
}